<template>
    <div :id="id" class="container" ref="echart"></div>
</template>
<script>
export default {
    name: "stepLine",
    props: {
        myData: {
            type: Object,
            default: () => {},
        },
        requstParams: {
            type: Object,
            default: () => {},
        },
    },
    data() {
        return {
            id:'myStep',
            timer:null,
            chartView: null, 
            option: {
                backgroundColor:'#0a295b',
                title: {
                    text: "",
                },
                tooltip: {
                    trigger: "axis",
                    axisPointer: {
                        type: "cross",
                        label: {
                            backgroundColor: "#6a7985",
                        },
                    },
                },
                legend: {
                    icon: "square",
                    orient: "vertical",
                    right: "0%",
                    top: "10%",
                    data: [
                        {
                            name: "",
                            itemStyle: {
                                color: "#0bffff",
                            },
                            textStyle: {
                                color: "#0bffff",
                            },
                        },
                        {
                            name: "",
                            itemStyle: {
                                color: "#14dc28",
                            },
                            textStyle: {
                                color: "#14dc28",
                            },
                        },                       
                    ],
                },
                grid: {
                    left: "3%",
                    right: "12%",
                    bottom: "3%",
                    containLabel: true,
                },
                xAxis: {
                    name: "",
                    type: "category",
                     boundaryGap:false,
                    axisTick: { show: false },
                     axisLabel:{
                            rotate:-20,
                            
                            },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: "#FFFFFF",
                        },
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            width: 2,
                            color: ["#094762"],
                            type: "dashed",
                        },
                    },
                    data: [],
                },
                yAxis: {
                    name: "",
                    type: "value",
                    axisLine:{
                            show: true ,
                            lineStyle: {
                                color: '#FFFFFF'
                            },                          
                    },
                    axisLabel: {
                         show: true,
          
                    },    
                    splitLine: {
                        show: true,
                        lineStyle: {
                            width: 2,
                            color: ["#094762"],
                            type: "dashed",
                        },
                    },                   
                },
                series: [],
            },
            chartTopic:this.requstParams.chartTopic,//主题名
            modelName:this.requstParams.modelName,//模块名
            linkName:this.requstParams.linkName,//连接名
            isUseWs:this.requstParams.isUseWs,
            intervalTime:this.requstParams.intervalTime,
            isUseTimer:this.requstParams.isUseTimer,
        };
    },
    components: {},
    created(){
        // this.initData()
    },
    mounted() {
         this.initChart();
        // 请求初始化数据
        this.$nextTick(() => {
            console.log(this.requstParams);
            let url = this.requstParams.initUrl;
            let method = this.requstParams.initMethod;
            if (url && method) {
                this.init(method, url);
            }
        });
    },
    beforeDestroy() {
        // if (!this.chartView) {
        //     return;
        // }
        // this.chartView.dispose();
        // this.chartView = null;
        clearInterval(this.timer);
        this.timer=null;
    },
    watch: {
        myData: {
             handler(val) {
                if (val) {
                    // this.destroyCharts();
                    this.initData();
                    this.initChart();
                }
            },
            deep: true, 
        },
        requstParams: {
            handler(val) {
                // 用于echart的画图的id，当相同图表同时渲染是，id可作用唯一键
                this.id = val.id
                console.log("myParam", val);
                if (val.newHeight || val.newWidth) {
                    this.resizeContainer();
                }
                if (val.xFormatter || val.yFormatter) {
                    this.destroyCharts();
                    this.initData();
                    this.initChart();
                }
                if(val.isUseTimer){
                    // 先清除定时器
                    clearInterval(this.timer);
                    this.timer = null;
                    // 重新使用新的时间间隔开启一个新的定时器
                    this.myTimer(val.intervalTime);
                }else{
                     clearInterval(this.timer);
                     this.timer=null;
                }
                if(val.isUseWs){
                    this.wsSubscribe();
                }else{
                    this.cancelSubscribe();
                }
            },
            immediate: true,
            deep: true,
        },
    },
    methods: {
        initChart() {
            let dom = document.getElementById(this.id);
            if (dom) {
                this.chartView = this.$echarts.init(
                    document.getElementById(this.id)
                );
                this.chartView.setOption(this.option);
                let myChart = this.chartView;
                window.addEventListener("resize", () => {
                    myChart.resize();
                });
            }
        },
        initData() {
            console.log('ddd',this.myData)
            this.option.backgroundColor = this.myData.backgroundColor;
            this.option.title.show = this.myData.title.show;
            this.option.title.text = this.myData.title.text;
            this.option.title.left = this.myData.title.left;
            this.option.title.top = this.myData.title.top;
           this.option.legend.data= this.myData.legend.data;
            //判断X轴是否有formartter配置
            // if (this.requstParams.xFormatter) {
            //     this.option.xAxis.axisLabel.formatter = this.xAxisFormatter(
            //         this.requstParams
            //     );
            // } else {
            //     this.option.xAxis.axisLabel.formatter = (value) => {
            //         return value;
            //     };
            // }
           this.option.xAxis.show = this.myData.xAxis.show;
           this.option.xAxis.data= this.myData.xAxis.data;
           this.option.xAxis.name= this.myData.xAxis.name;
           this.option.yAxis.show = this.myData.yAxis.show;
           this.option.yAxis.name= this.myData.yAxis.name;
          //判断Y轴是否有formartter配置
            // if (this.requstParams.yFormatter) {
            //     this.option.yAxis.axisLabel.formatter = this.yAxisFormatter(
            //         this.requstParams
            //     );
            // } else {
            //     this.option.yAxis.axisLabel.formatter = (value) => {
            //         return value;
            //     };
            // }
           for(let i in this.myData.series){
            let serie = this.myData.series[i];
            serie.type = 'line';
            this.option.series.push(serie);

           }
        },
         //***发送请求****
        getData(method, url, params) {
            return this.$myAxios.request(method, url, params).then((res) => {
                return res;
            });
        },
        //接口数据
        async init(method, url, requstForm) {
            console.log("init:", method, url, requstForm);
            if (url && url != "" && method && method != "") {
                let res = await this.getData(method, url, requstForm);
                console.log("接口数据", res);
                // this.$set(this.option.title, "text", res.data.data.title.text);
                // this.$set(
                //     this.option.legend,
                //     "data",
                //     res.data.data.legend.data
                // );
                 //判断X轴是否有formartter配置
                // if (this.requstParams.xFormatter) {
                // this.option.xAxis.axisLabel.formatter = this.xAxisFormatter(
                //     this.requstParams
                // );
                // } else {
                //     this.option.xAxis.axisLabel.formatter = (value) => {
                //         return value;
                //     };
                // }
                  //判断X轴是否有formartter配置
                if (this.requstParams.xFormatter) {
                    let xData = eval(this.requstParams.xFormatter)(res);
                    this.$set(this.option.xAxis, "data", xData);
                }
                if (this.requstParams.yFormatter) {
                    let serie = this.option.series[0]
                    let serieCopy 
                    let series = []
                    let yData = eval(this.requstParams.yFormatter)(res);
                    for (let i in yData) {
                        serieCopy = JSON.parse(JSON.stringify(serie))
                        serieCopy.type = "line";
                        serieCopy.data = yData[i]
                        series.push(serieCopy);
                        serieCopy = null
                    }
                     this.$set(this.option, "series", series);
                }
                // 刷新echart的图表
                this.initChart();
                // this.$set(this.option.xAxis, "data", res.data.data.xAxis.data);
                // this.$set(this.option.xAxis, "name", res.data.data.xAxis.name);
                // this.$set(this.option.yAxis, "name", res.data.data.yAxis.name);
                 //判断Y轴的formartter
                // if (this.requstParams.yFormatter) {
                // this.option.yAxis.axisLabel.formatter = this.yAxisFormatter(
                //     this.requstParams
                // );
                // } else {
                //     this.option.yAxis.axisLabel.formatter = (value) => {
                //         return value;
                //     };
                // }
                // let result = res.data.data.series;
                // for (let i in result) {
                //     let serie = result[i];
                //     serie.type = "line";
                //     this.option.series.push(serie);
                // }
            }
        },
        //X轴formartter
        xAxisFormatter(requstForm) {
            let xFormatter;
            if (typeof requstForm.xFormatter != "function") {
                xFormatter = eval(requstForm.xFormatter);
            } else {
                xFormatter = requstForm.xFormatter;
            }
            return xFormatter;
        },
        //y轴formartter
        yAxisFormatter(requstForm) {
            let yFormatter;
            if (typeof requstForm.yFormatter != "function") {
                yFormatter = eval(requstForm.yFormatter);
            } else {
                yFormatter = requstForm.yFormatter;
            }
            return yFormatter;
            // return yFormatter(item);
        },
        //将传入的参数--组装为一个对象
        getInitParam() {
            let objRequst = {};
            if (
                this.requstParams.initRequstForm &&
                this.requstParams.initRequstForm.length > 0
            ) {
                this.requstParams.initRequstForm.forEach((val) => {
                    objRequst[val.label] = val.value;
                });
            }
            return objRequst;
        },
        resizeContainer(){
            console.log('888888')
             let container = document.getElementById(this.id);
              container.style.width =this.requstParams.newWidth;
              container.style.height =this.requstParams.newHeight;
             this.chartView.resize();
        },
        destroyCharts() {
            if (
                this.chartView != null &&
                this.chartView != "" &&
                this.chartView != undefined
            ) {
                this.chartView.dispose();
            }
            // this.chartView=Echarts.init(this.$refs.chart)
            this.option.series = [];
        },
        //add**
        addSeries() {
            let result = [
                { name: "A", data: [0.8, 0.3, 0.8, 0.4, 1, 0.4, 1] },
                { name: "B", data: [0.7, 1, 0.7, 0.6, 1, 0.6, 1] }               
            ];
            // let newResult = [];
            if (result.length) {
                result.forEach((item) => {
                    this.option.series.push({
                        step: 'start',
                        type: "line",
                        ...item,
                    });
                });
            }        
            // this.option.series=newResult;
            this.$nextTick(() =>{  
                this.chartView.dispose();
                this.initChart();
            })   
        },
        //update**
        updateApi(){
            this.destroyCharts();
            this.initData();
            this.initChart();

        },
        //timer**
        myTimer(intervalTime){        
            this.timer = setInterval(()=>{
                // this.destroyCharts();
                // this.initData();
                // this.initChart();
                let url = this.requstParams.initUrl;
                let method = this.requstParams.initMethod;
                if (url && method) {
                    this.init(method, url);
                }
            },intervalTime)
        },
        //连接websocket
        wsSubscribe(par) {
            let header = {}
            if (par && Object.keys(par).length > 0) {
                Object.assign(header, par)
            }
            let that = this;
            let model= {}
            this.$set(model,this.modelName,(res) => {
                        this.$set(this.option.series[0], "data", res.data['val']);
                        this.$set(this.option.xAxis,'data',res.data['time'])
                        console.log("【universalSession】数据来了")
                        this.initChart();
                    })
            let subscriber = {
                topic: that.chartTopic,
                model: model
            }
            //发起topic主题订阅
            let ws = this.$ws.getWs(this.linkName);
            if(!ws){
                console.log("ws未连接")
            }else{
                ws.subscribeToModel(subscriber.topic, subscriber.model, header);
            }
        },
        //取消订阅
        cancelSubscribe(){
            let ws = this.$ws.getWs(this.linkName);
            if(ws){
                ws.unSubscribe(this.chartTopic);
            }
           
        },
    },
};
</script>
<style lang="less" scoped>
.container {
    height: 460px;
    width: 30vw;
    margin: 0px 33px 0 33px;
}
</style>